# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, get_object_or_404
from website1.models import Movie, Log, Classifies
from website1.cloudfiles.downloader import Downloader
from website1.cloudfiles.turing import turing, rtextreplace
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import time
from django.http import HttpResponseRedirect, HttpResponse
# Create your views here.


def toindex(request):
    """跳转到index界面"""
    return HttpResponseRedirect('/index')


def movie(request, id=1, number=1):
    """播放视频"""
    context = dict.fromkeys(['picurl', 'fileurl', 'number'], 'unknow')
    movie = get_object_or_404(Movie, id=id)
    movie.playcount += 1
    movie.save()
    if movie.isoutsource == '1':
        movie.avaliblesum=[]
        #movie.avaliblesum=movie.outsource_set.count()
        for outsource in movie.outsource_set.all():
            if int(outsource.num) == int(number):
                context['fileurl'] = outsource.outfilelink
            movie.avaliblesum.append(str(outsource.num))
    else:
        prefilename = movie.prefilename
        number = '%03d' % int(number)
        filename = prefilename + number + movie.suffixname
        number = str(int(number))
        downloader = Downloader()
        context['fileurl'] = downloader.getprivateurl(filename)
        tmp = []
        for item in range(1, movie.avaliblesum+1):
            tmp.append(str(item))
        movie.avaliblesum = tmp
    context['movie'] = movie
    context['number'] = number
    getmenu(context)
    w2dblog(request, id=id, number=number)
    return render(request, 'movie.html', context)


def index(request):
    context = {}
    getmenu(context)
    results = []
    for classify in context['classifies']:
        #key = str(classify.classkey)
        movies = classify.movie_set.filter(weight__gte=5).order_by('-createtime')[:12]
        #movies = Movie.objects.filter(weight__gte=5).filter(classkey=key).order_by('-createtime')[:12]
        results.append((classify, movies))
    context['results'] = results
    w2dblog(request)
    return render(request, 'index.html', context)


def detail(request, id = 1):
    movie = get_object_or_404(Movie, id=id)
    movie.clickcount += 1
    movie.save()
    context = dict.fromkeys(['picurl'], 'unknow')
    context['picurl'] = movie.picurl
    getmenu(context)
    if movie.isoutsource == '0':
        tmp = []
        for item in range(1, movie.avaliblesum+1):
            tmp.append(str(item))
        movie.avaliblesum = tmp
    else:
        movie.avaliblesum = []
        for outsource in movie.outsource_set.all():
            movie.avaliblesum.append(str(outsource.num))
    context['movie'] = movie
    w2dblog(request, id=id)
    return render(request, 'detail.html', context)


def classsearch(request, classkey='1001', page=1):
    context = {}
    getmenu(context)
    classify = Classifies.objects.get(classkey=classkey)
    allmovies = classify.movie_set.all()
    p = Paginator(allmovies, 24)
    sum = p.num_pages
    page = int(page)
    try:
        movies = p.page(page).object_list
    except PageNotAnInteger:
        movies = p.page(1).object_list
    except EmptyPage:
        movies = p.page(p.num_pages).object_list
    context['movies'] = movies
    context['classify'] = classify
    context['page'] = page
    context['sum'] = sum
    pagenumlisttmp = [1, 2, 3, 4, 5, 6]
    if sum <= 6 :
        pagenumlisttmp = range(1, sum+1)
    elif page <= 3:
        pass
    elif page > sum-3:
        pagenumlisttmp = range(sum-5, sum+1)
    else:
        pagenumlisttmp = range(page-2, page+4)
    context['pagenumlist'] = pagenumlisttmp
    context['updown'] = [page-1, page+1]
    w2dblog(request, classkey=classkey, page=page)
    return render(request, 'classsearch.html', context)


def keywordsearch(request, page=1):
    key = request.POST.get('wd', '')
    context = {}
    getmenu(context)
    allmovies = Movie.objects.filter(Q(keyword__icontains=key) | Q(moviename__icontains=key))
    p = Paginator(allmovies, 24)
    try:
        movies = p.page(page).object_list
    except PageNotAnInteger:
        movies = p.page(1).object_list
    except EmptyPage:
        movies = p.page(p.num_pages).object_list
    context['movies'] = movies
    context['key'] = key
    context['page'] = page
    w2dblog(request, key=key, page=page)
    return render(request, 'keywordsearch.html', context)


def chat(request):
    msg = request.POST.get('msg', '')
    return HttpResponse(rtextreplace(turing(msg)))

def w2dblog(request, **params):
    paramsstr = ''
    url = request.get_full_path()
    method = request.method
    ip = ''
    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
        ip = request.META.get('HTTP_X_FOEWARDED_FOR')
    else:
        ip = request.META.get('REMOTE_ADDR')
    righttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+3600*8))#utc转东8区时间
    for k, v in params.items():
        paramsstr += str(k)+'='+str(v)+'&&'
    log = Log(righttime=righttime, url=url, ip=ip, params=paramsstr, method=method)
    log.save()


def getmenu(context):
    context['classifies'] = Classifies.objects.all().order_by('-weight')

